using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Threading;

namespace Ricciolo.StylesExplorer.Model
{
    class NotifyObject : Component, INotifyPropertyChanged
    {
        private static PropertyChangedEventHandler _propertyChanged;
        private ISynchronizeInvoke _invoker;

        public NotifyObject()
        {
            _invoker = WinFormSynchronizeInvoke.Current;
        }

        #region INotifyPropertyChanged Members

        ///<summary>
        ///Occurs when a property value changes.
        ///</summary>
        ///
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add { _propertyChanged += value; }
            remove { _propertyChanged -= value; }
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (_propertyChanged != null)
                if (this.CheckAccess())
                    _propertyChanged(this, e);
                else
                    this.Invoker.BeginInvoke(_propertyChanged, new object[] { this, e });
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        protected ISynchronizeInvoke Invoker
        {
            get { return _invoker; }
        }

        protected void VerifyAccess()
        {
            if (_invoker.InvokeRequired)
                throw new InvalidOperationException("You must call method only from main thread");
        }

        protected bool CheckAccess()
        {
            return !_invoker.InvokeRequired;
        }
    }
}
